package jmine.tec.di.type;


import bancosys.tec.persist.Persistable;
import bancosys.tec.persist.dao.BaseDAO;
import bancosys.tec.persist.dao.BaseDAOFactory;
import bancosys.tec.persist.dao.BeanNotFoundException;

/**
 * {@link TypeConverter} para {@link Persistable}
 * 
 * @author takeshi
 */
public class PersistableTypeConverter implements TypeConverter<Persistable> {

    private final BaseDAOFactory baseDAOFactory;

    /**
     * @param baseDAOFactory o {@link BaseDAOFactory}
     */
    public PersistableTypeConverter(BaseDAOFactory baseDAOFactory) {
        super();
        this.baseDAOFactory = baseDAOFactory;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public Persistable convert(String value, Class<?> desiredType) throws TypeConvertionException {
        Class<Persistable> someClass = (Class<Persistable>) desiredType;
        BaseDAO<Persistable> dao = this.baseDAOFactory.getGenericDAO(someClass);
        try {
            if (value.matches("\\d+")) {
                return dao.findByPk(Long.valueOf(value));
            } else {
                return dao.findByNaturalKey(value);
            }
        } catch (NumberFormatException e) {
            throw new TypeConvertionException(e, desiredType, value);
        } catch (BeanNotFoundException e) {
            throw new TypeConvertionException(e, desiredType, value);
        }
    }

    /**
     * {@inheritDoc}
     */
    public boolean isTypeCompatible(Class<?> declaredRawType) {
        return Persistable.class.isAssignableFrom(declaredRawType);
    }

}
